package com.syqc.comlib.utils

import com.syqc.comlib.base.Base64.decode
import com.syqc.comlib.base.Base64.encode
import com.syqc.comlib.utils.MLog.e
import java.security.MessageDigest
import java.security.SecureRandom
import javax.crypto.Cipher
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.DESKeySpec

object CoderUtil {
    private val HEX_CHARS = "0123456789abcdef".toCharArray()
    private const val MD5 = "MD5"
    private const val RSA = "RSA"
    private const val DES = "DES"
    private const val UTF_8 = "UTF-8"
    const val DES_KEY = "0123456789abcdefghigkmnopqrstuvwxyz"

    // MD5加密
    fun md5Encrypt(s: String): String {
        try {
            val digest = MessageDigest.getInstance(MD5)
            digest.update(s.toByteArray())
            val buf = digest.digest()
            val chars = CharArray(2 * buf.size)
            for (i in buf.indices) {
                chars[2 * i] = HEX_CHARS[buf[i].toInt() and 0xF0 ushr 4]
                chars[2 * i + 1] = HEX_CHARS[buf[i].toInt() and 0x0F]
            }
            return String(chars)
        } catch (e: Exception) {
            e(e.message)
        }
        return ""
    }

    // DES加密
    @Throws(Exception::class)
    fun desEncrypt(data: String, key: String): String {
        val sr = SecureRandom()
        val dks = DESKeySpec(key.toByteArray())
        val keyFactory = SecretKeyFactory.getInstance(DES)
        val securekey = keyFactory.generateSecret(dks)
        val cipher = Cipher.getInstance(DES)
        cipher.init(Cipher.ENCRYPT_MODE, securekey, sr)
        return encode(cipher.doFinal(data.toByteArray()))
    }

    // DES解密
    @Throws(Exception::class)
    fun desDecrypt(data: String, key: String): String {
        val sr = SecureRandom()
        val dks = DESKeySpec(key.toByteArray())
        val keyFactory = SecretKeyFactory.getInstance(DES)
        val securekey = keyFactory.generateSecret(dks)
        val cipher = Cipher.getInstance(DES)
        cipher.init(Cipher.DECRYPT_MODE, securekey, sr)
        return String(cipher.doFinal(decode(data)))
    }

}